<template>
	<view class="menu-box left clearfix">
		<view class="home-titles left clearfix">
			当前时间:{{ datetime }}
		</view>
		
		<!--内容开始-->
		<view class="home-content left clearfix">
			
			<!--按钮开始-->
			<view class="home-button-box left clearfix">
				
				<view class="home-button-item left clearfix">
					<view class="home-button-left left clearfix">
						<text>{{ todayOrderCount }}</text>
						<text>今日订单</text>
					</view>
					<view class="home-button-right right">
						<image src="/static/images/dingdan-order.png" mode="aspectFill"></image>
					</view>
				</view>
				
				<view class="home-button-item left clearfix">
					<view class="home-button-left left clearfix">
						<text>{{ visitorCount }}</text>
						<text>今日访客</text>
					</view>
					<view class="home-button-right right">
						<image src="/static/images/fangke-icon.png" mode="aspectFill"></image>
					</view>
				</view>
				
				<view class="home-button-item left clearfix">
					<view class="home-button-left left clearfix">
						<text>{{ pendingDeliveryCount }}</text>
						<text>待发订单</text>
					</view>
					<view class="home-button-right right">
						<image src="/static/images/daifahuodingdan.png" mode="aspectFill"></image>
					</view>
				</view>
				
				
				<view class="home-button-item left clearfix">
					<view class="home-button-left left clearfix">
						<text>{{ afterSalesCount }}</text>
						<text>售后订单</text>
					</view>
					<view class="home-button-right right">
						<image src="/static/images/shouhoudingdan.png" mode="aspectFill"></image>
					</view>
				</view>
				
				
			</view>
			<!--按钮结束-->
			
			
			<!--消息列表 - 循环展示消息-->
			<view class="home-message left clearfix" v-for="(message, index) in messageList" :key="message._id || index">
				<view class="home-message-title left clearfix">
					<label class="left">{{ message.title||message.type }}</label>
					<label class="right">{{ formatDate(message.create_date) }}</label>
				</view>
				<view class="home-message-content left  clearfix">
					{{ message.content }}
				</view>
				<view class="home-message-bottom left clearfix">
					<view class="right">
						<label><uni-icons type="icon-chuangzuo2" size="15" color="#999" custom-prefix="iconfont"></uni-icons></label>
						<label>收到</label>
					</view>
					
					<view class="right">
						<label><uni-icons type="icon-duihao2" size="15" color="#999" custom-prefix="iconfont"></uni-icons></label>
						<label>回复</label>
					</view>
					
					<view class="right" v-if="message.send_uid">
						@{{ message.send_user_name || '未知用户' }}
					</view>
				</view>
			</view>
			
			<!-- 无消息时显示 -->
			<view class="no-message" v-if="messageList.length === 0">
				暂无消息
			</view>
			
			
			
			
		</view>
		<!--内容结束-->
	</view>
</template>


<style scoped>
	.home-titles{width:calc(100% - 20px);line-height:50px;padding-left:20px;font-size:16px;color:#666;}
	.home-button-right image{width:100%;height:100%;}
	.home-button-right{width:70px;height:70px;overflow: hidden;border-radius: 50%;margin:20px;}
	.home-button-left text:last-child{color:#fff;font-size:14px;}
	.home-button-left text:first-child{font-size:30px;line-height:50px;margin-top:18px;color:#fff;font-weight:500;}
	.home-button-left text{float:left;text-align: center;width:100%;margin-left:10px;}
	.home-button-item{width:24%;height:110px;margin-top:10px;margin-left:.5%;margin-right:.5%;background: linear-gradient(90deg, #4287fe, #298bfe 25%, #0f8ffd 51%, #25b4c1);transition: all .3s;border-radius: 10px;transition: all .3s;cursor:pointer;}
	.home-button-box{width:100%;height:130px;background:#e6f0ff;border-radius: 10px;margin-bottom:30px;}
	.home-message-bottom view:hover{color:#2979ff;}
	.home-message-bottom view label{margin-right:2px;cursor:pointer;}
	.home-message-bottom view{line-height:40px;height:40px;margin-right:20px;font-size:14px;color:#999;}
	.home-message-bottom{height:40px;line-height:40px;width:100%;}
	.home-message-content{color:#777;line-height:25px;padding-top:10px;padding-bottom:10px;font-size:14px;}
	.home-message-title label:last-child{font-size:14px;color:#999;}
	.home-message-title label:first-child{line-height:40px;font-weight:500;color:#2979ff;}
	.home-message-title{width:100%;height:40px;border-bottom:1px solid #eee;font-size:14px;line-height:40px;}
	.home-message{width:calc(100% - 40px);min-height:100px;background:#f1f5fb;padding:20px;border-radius: 10px;padding-top:0;margin-bottom:20px;padding-bottom:0px;}
	.home-content{width:96%;margin-left:2%;margin-top:10px;min-height:500px;}
	.no-message{width:100%;text-align:center;padding:30px 0;color:#999;font-size:16px;}
</style>


<script>
// 引入数据库
var db = uniCloud.database()
var cmd = db.command

export default {
	name:"index-home",
	data() {
		return {
			datetime: '',
			todayOrderCount: 0,      // 今日订单总数
			visitorCount: 0,         // 今日访客数
			pendingDeliveryCount: 0,  // 待发货订单数
			afterSalesCount: 0,       // 售后订单数
			messageList: [],          // 消息列表
			is24HourFormat: true      // 时间格式标记
		};
	},
	mounted() {
		// 更新时间
		this.updateTime();
		this.timer = setInterval(() => {
			this.updateTime();
		}, 1000);
		
		// 获取统计数据
		this.getStatistics();
		
		// 获取消息列表
		this.getMessages();
	},
	onUnload() {
		clearInterval(this.timer);
	},
	props:{
		userinfo:{
			type:Object,
			default:{}
		}
	},
	methods: {
		// 获取所有统计数据
		getStatistics() {
			// 获取今天的开始和结束时间
			const today = new Date();
			today.setHours(0, 0, 0, 0);
			const todayStart = today.getTime();
			const todayEnd = todayStart + 24 * 60 * 60 * 1000 - 1;
			
			// 获取订单统计数据
			this.getOrderStatistics(todayStart, todayEnd);
			// 获取访客统计数据
			this.getVisitorStatistics(todayStart, todayEnd);
		},
		
		// 获取订单统计数据
		getOrderStatistics(todayStart, todayEnd) {
			// 1. 查询今日订单总数（今天创建的所有订单）
			db.collection('order')
				.where({
					create_date: cmd.gte(todayStart).and(cmd.lte(todayEnd))
				})
				.count()
				.then(res => {
					this.todayOrderCount = res.result.total || 0;
				})
				.catch(err => {
					console.error('获取今日订单数失败:', err);
				});
			
			// 2. 查询待发货订单（已支付但未发货：status_code=1）
			db.collection('order')
				.where({
					status_code: 1
				})
				.count()
				.then(res => {
					this.pendingDeliveryCount = res.result.total || 0;
				})
				.catch(err => {
					console.error('获取待发货订单数失败:', err);
				});
			
			// 3. 查询售后订单（申请退款和已退款：status_code=4或5）
			db.collection('order')
				.where({
					status_code: cmd.in([4, 5])
				})
				.count()
				.then(res => {
					this.afterSalesCount = res.result.total || 0;
				})
				.catch(err => {
					console.error('获取售后订单数失败:', err);
				});
		},
		
		// 获取访客统计数据
		getVisitorStatistics(todayStart, todayEnd) {
			// 查询今日所有访客记录
			db.collection('visitor')
				.where({
					create_date: cmd.gte(todayStart).and(cmd.lte(todayEnd))
				})
				.get()
				.then(res => {
					if (res.result.data && res.result.data.length > 0) {
						// 计算总访问次数（累加所有记录的number字段）
						const totalVisits = res.result.data.reduce((sum, item) => {
							return sum + (item.number || 0);
						}, 0);
						
						// 计算独立访客数（基于ip去重）
						const uniqueIps = new Set();
						res.result.data.forEach(item => {
							if (item.ip) {
								uniqueIps.add(item.ip);
							}
						});
						
						// 这里使用总访问次数作为访客数显示
						// 如果需要显示独立访客数，可以使用 uniqueIps.size
						this.visitorCount = totalVisits;
					} else {
						this.visitorCount = 0;
					}
				})
				.catch(err => {
					console.error('获取访客数据失败:', err);
				});
		},
		
		// 获取最新5条消息
		getMessages() {
			if (!this.userinfo || !this.userinfo._id) {
				console.error('用户信息不存在，无法获取消息');
				return;
			}
			
			// 查询当前用户的消息，按创建时间倒序，取最新5条
			db.collection('message')
				.where({
					uid: this.userinfo._id,
					type:db.command.neq('系统消息')
				})
				.orderBy('create_date', 'desc')
				.limit(5)
				.get()
				.then(res => {
					if (res.result && res.result.data) {
						this.messageList = res.result.data;
						// 如果需要获取发送人的用户名，可以在这里继续查询用户表
						// this.getMessageSenderNames();
					}
				})
				.catch(err => {
					console.error('获取消息失败:', err);
				});
		},
		
		// 格式化日期显示
		formatDate(timestamp) {
			if (!timestamp) return '';
			
			// 处理时间戳（兼容秒级和毫秒级）
			if (timestamp.toString().length === 10) {
				timestamp = timestamp * 1000;
			}
			
			const date = new Date(timestamp);
			const year = date.getFullYear();
			const month = this.padZero(date.getMonth() + 1);
			const day = this.padZero(date.getDate());
			const hours = this.padZero(date.getHours());
			const minutes = this.padZero(date.getMinutes());
			
			return `${year}-${month}-${day} ${hours}:${minutes}`;
		},
		
		// 更新时间显示
		updateTime() {
			const now = new Date();
			
			// 格式化日期部分
			const year = now.getFullYear();
			const month = this.padZero(now.getMonth() + 1);
			const day = this.padZero(now.getDate());
			
			// 格式化时间部分
			let hours = now.getHours();
			const minutes = this.padZero(now.getMinutes());
			const seconds = this.padZero(now.getSeconds());
			
			// 12小时制转换
			let period = 'AM';
			if (!this.is24HourFormat) {
				period = hours >= 12 ? '下午' : '上午';
				hours = hours % 12;
				hours = hours ? hours : 12; // 0 应显示为 12
			}
			
			// 格式化时间字符串
			const timeString = this.is24HourFormat 
				? `${hours}:${minutes}:${seconds}` 
				: `${period} ${hours}:${minutes}:${seconds}`;
			
			// 格式化日期和时间在一行
			this.datetime = `${year}年${month}月${day}日 ${timeString}`;
			
			// 更新时分秒
			this.hour = this.padZero(hours);
			this.minute = minutes;
			this.second = seconds;
			
			// 添加秒针动画
			this.secondClass = 'scale-110 text-secondary';
			setTimeout(() => {
				this.secondClass = '';
			}, 500);
		},
		
		// 数字补零
		padZero(num) {
			return String(num).padStart(2, '0');
		},
		
		// 切换时间格式
		toggleFormat() {
			this.is24HourFormat = !this.is24HourFormat;
			this.updateTime();
			
			// 添加切换动画
			const query = uni.createSelectorQuery().in(this);
			query.select('.datetime').boundingClientRect(data => {
				const animation = uni.createAnimation({
					duration: 300,
					timingFunction: 'ease'
				});
				animation.scale(1.05).opacity(0.7).step();
				animation.scale(1).opacity(1).step();
				this.setData({
					datetimeAnimation: animation.export()
				});
			}).exec();
		}
	}
}
</script>
